<template>
  <view class="container">
    <view class="header">
      <text class="title">缴费支付</text>
    </view>
    <view class="bill-info-card">
      <view class="bill-header-info">
        <view class="bill-type">{{ billDetail.bill_type }}</view>
        <view class="bill-address">{{ billDetail.remarks || '无地址信息' }}</view>
        <view class="bill-period">账单周期：{{ billDetail.bill_period || '无周期信息' }}</view>
      </view>
      <view class="bill-amount">
        <text class="amount-label">应缴金额</text>
        <text class="amount-value">¥{{ billDetail.amount }}</text>
      </view>
    </view>
    
    <view class="payment-card">
      <view class="card-title">支付方式</view>
      <view class="payment-methods">
        <view 
          class="payment-method-item" 
          v-for="(method, index) in paymentMethods" 
          :key="index"
          :class="{ active: selectedPayment === method.value }"
          @click="selectPayment(method.value)"
        >
          <image class="payment-icon" :src="method.icon"></image>
          <view class="payment-info">
            <text class="payment-name">{{ method.name }}</text>
            <text class="payment-desc">{{ method.desc }}</text>
          </view>
          <view class="payment-check">
            <view class="check-circle" v-if="selectedPayment === method.value">
              <view class="check-inner"></view>
            </view>
            <view class="check-circle" v-else></view>
          </view>
        </view>
      </view>
    </view>
    
    <view class="detail-card">
      <view class="card-title">账单明细</view>
      <view class="detail-item" v-for="(item, index) in billDetail.details" :key="index">
        <text class="detail-name">{{ item.name }}</text>
        <text class="detail-value">¥{{ item.value }}</text>
      </view>
      <view class="detail-total">
        <text class="total-label">合计</text>
        <text class="total-value">¥{{ billDetail.amount }}</text>
      </view>
    </view>
    
    <!-- 添加账单备注区域 -->
    <view class="remark-card">
      <view class="card-title">缴费须知</view>
      <view class="remark-content">
        <view class="remark-item">
          <text class="remark-icon">•</text>
          <text class="remark-text">请确保您的账户余额充足，避免支付失败</text>
        </view>
        <view class="remark-item">
          <text class="remark-icon">•</text>
          <text class="remark-text">支付成功后系统将自动为您生成电子收据</text>
        </view>
        <view class="remark-item">
          <text class="remark-icon">•</text>
          <text class="remark-text">如有疑问，请联系物业客服：400-123-4567</text>
        </view>
        <view class="remark-item">
          <text class="remark-icon">•</text>
          <text class="remark-text">支付记录可在"我的账单"中查看</text>
        </view>
      </view>
    </view>
    
    <view class="agreement">
      <checkbox :checked="isAgree" @click="isAgree = !isAgree" style="transform:scale(0.7)" />
      <text class="agreement-text">
        我已阅读并同意 <text class="link" @click="openAgreement">《缴费协议》</text>
      </text>
    </view>
    
    <!-- 底部固定栏 - 使用安全区域 -->
    <view class="safe-area-inset-bottom">
      <view class="bottom-bar">
        <view class="payment-info">
          <text class="payment-amount-label">支付金额</text>
          <text class="payment-amount-value">¥{{ billDetail.amount }}</text>
        </view>
        <button 
          class="payment-btn" 
          :class="{ disabled: !isAgree || !selectedPayment }"
          :disabled="!isAgree || !selectedPayment"
          @click="confirmPayment"
          type="primary"
        >
          确认支付
        </button>
      </view>
    </view>

  </view>
</template>

<script>
import { getBillDetail, payBill } from '../../api/billing.js';

export default {
  data() {
    return {
      id: null,
      selectedPayment: 'wechat',
      isAgree: true,
      showDebug: true, // 显示调试信息
      billDetail: {
        bill_number: '',
        bill_type: '',
        payment_status: '',
        bill_period: '',
        remarks: '',
        amount: '0.00',
        due_date: ''
      },
      paymentMethods: [
        {
          name: '微信支付',
          value: 'wechat',
          icon: '/static/wechat_pay.png',
          desc: '推荐使用微信支付'
        },
        {
          name: '支付宝',
          value: 'alipay',
          icon: '/static/alipay.png',
          desc: '支付宝安全支付'
        },
        {
          name: '银行卡支付',
          value: 'bank',
          icon: '/static/bank_pay.png',
          desc: '支持储蓄卡和信用卡'
        }
      ]
    }
  },
  onLoad(options) {
    console.log('支付页面接收到的参数:', options);
    // 检查URL中的id参数
    if (options.id) {
      this.id = options.id;
      console.log('设置账单ID:', this.id);
      this.fetchBillDetail();
    } else {
      // 尝试从页面路径中提取ID
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const fullPath = currentPage.route + currentPage.$page.fullPath;
      console.log('当前页面完整路径:', fullPath);
      
      // 尝试从URL中提取ID
      const match = fullPath.match(/payment\?id=([^&]+)/);
      if (match && match[1]) {
        this.id = match[1];
        console.log('从URL提取的账单ID:', this.id);
        this.fetchBillDetail();
      } else {
        uni.showToast({
          title: '未找到账单ID',
          icon: 'none'
        });
        // 3秒后返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 3000);
      }
    }
  },
  methods: {
    // 获取账单详情
    fetchBillDetail() {
      // 检查ID是否有效
      if (!this.id || this.id === 'null' || this.id === 'undefined') {
        uni.showToast({
          title: '无效的账单ID',
          icon: 'none'
        });
        console.error('无效的账单ID:', this.id);
        return;
      }
      
      uni.showLoading({
        title: '加载中...'
      })
      
      console.log('正在获取账单详情，ID:', this.id);
      getBillDetail(this.id).then(res => {
        if (res.code === 200 && res.data) {
          this.billDetail = res.data
          
          // 检查账单是否已支付
          if (this.billDetail.payment_status === '已支付') {
            uni.showModal({
              title: '提示',
              content: '该账单已支付',
              showCancel: false,
              success: () => {
                uni.navigateBack()
              }
            })
          }
        } else {
          uni.showToast({
            title: res.message || '获取账单详情失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        console.error('获取账单详情失败:', err)
        uni.showToast({
          title: '获取账单详情失败，请稍后重试',
          icon: 'none'
        })
      }).finally(() => {
        uni.hideLoading()
      })
    },
    
    // 选择支付方式
    selectPayment(payment) {
      this.selectedPayment = payment
    },
    
    // 打开协议
    openAgreement() {
      uni.showToast({
        title: '缴费协议内容',
        icon: 'none'
      })
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 确认支付
    confirmPayment() {
      if (!this.isAgree) {
        uni.showToast({
          title: '请先同意缴费协议',
          icon: 'none'
        })
        return
      }
      
      if (!this.selectedPayment) {
        uni.showToast({
          title: '请选择支付方式',
          icon: 'none'
        })
        return
      }
      
      // 检查ID是否有效
      if (!this.id || this.id === 'null' || this.id === 'undefined') {
        uni.showToast({
          title: '无效的账单ID，无法支付',
          icon: 'none'
        });
        console.error('支付失败：无效的账单ID:', this.id);
        return;
      }
      
      // 显示支付中
      uni.showLoading({
        title: '支付处理中...'
      })
      
      // 生成交易号
      const transactionId = 'TX' + new Date().getTime() + Math.floor(Math.random() * 1000)
      
      console.log('发起支付请求，账单ID:', this.id, '支付方式:', this.selectedPayment);
      
      // 保存支付方式和交易号到本地存储，供成功页面使用
      uni.setStorageSync('paymentMethod', this.selectedPayment);
      uni.setStorageSync('transactionId', transactionId);
      
      // 调用支付API
      payBill(this.id, {
        payment_method: this.selectedPayment,
        transaction_id: transactionId
      }).then(res => {
        uni.hideLoading()
        
        if (res.code === 200) {
          // 支付成功
          uni.showModal({
            title: '支付成功',
            content: '您已成功完成缴费',
            showCancel: false,
            success: () => {
              // 跳转到支付成功页面或返回账单列表
              uni.redirectTo({
                url: '/pages/billing/success?id=' + this.id
              })
            }
          })
        } else {
          // 支付失败
          uni.showModal({
            title: '支付失败',
            content: res.message || '支付处理失败，请稍后重试',
            showCancel: false
          })
        }
      }).catch(err => {
        uni.hideLoading()
        console.error('支付失败:', err)
        
        uni.showModal({
          title: '支付失败',
          content: '网络异常，请稍后重试',
          showCancel: false
        })
      })
    }
  }
}
</script>

<style>
.container {
  padding: 30rpx;
  padding-bottom: 250rpx;
  background-color: #F8F8F8;
  min-height: 100vh;
  box-sizing: border-box;
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.header {
  margin-bottom: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.back-btn {
  font-size: 28rpx;
  color: #007AFF;
}

.bill-info-card {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
  width: 100%;
}

.bill-header-info {
  width: 100%;
}

.bill-type {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.bill-address {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.bill-period {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.bill-amount {
  text-align: center;
  padding-top: 20rpx;
  padding-bottom: 10rpx;
  border-top: 1rpx solid #F2F2F2;
  width: 100%;
}

.amount-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.amount-value {
  font-size: 48rpx;
  color: #333;
  font-weight: bold;
}

.payment-card, .detail-card {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
  width: 100%;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  position: relative;
  padding-left: 20rpx;
}

.card-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 8rpx;
  height: 32rpx;
  width: 6rpx;
  background-color: #007AFF;
  border-radius: 3rpx;
}

.payment-methods {
  margin-top: 20rpx;
}

.payment-method-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #F2F2F2;
}

.payment-method-item:last-child {
  border-bottom: none;
}

.payment-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}

.payment-info {
  flex: 1;
}

.payment-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
  display: block;
}

.payment-desc {
  font-size: 24rpx;
  color: #999;
}

.payment-check {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-circle {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  border: 1rpx solid #CCCCCC;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-method-item.active .check-circle {
  border-color: #007AFF;
}

.check-inner {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background-color: #007AFF;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.detail-name {
  color: #666;
  font-size: 28rpx;
}

.detail-value {
  color: #333;
  font-size: 28rpx;
}

.detail-total {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #F2F2F2;
  width: 100%;
}

.total-label {
  color: #333;
  font-size: 28rpx;
  font-weight: bold;
}

.total-value {
  color: #333;
  font-size: 28rpx;
  font-weight: bold;
}

.remark-card {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
  width: 100%;
}

.remark-content {
  margin-top: 20rpx;
}

.remark-item {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.remark-icon {
  font-size: 28rpx;
  color: #007AFF;
  margin-right: 10rpx;
}

.remark-text {
  font-size: 28rpx;
  color: #333;
}

.agreement {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 30rpx;
  padding: 0 10rpx;
  width: 100%;
}

.agreement-text {
  font-size: 26rpx;
  color: #666;
}

.link {
  color: #007AFF;
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background-color: #FFFFFF;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
  z-index: 9999;
}

.payment-info {
  flex: 1;
}

.payment-amount-label {
  font-size: 26rpx;
  color: #666;
}

.payment-amount-value {
  font-size: 36rpx;
  color: #FF3B30;
  font-weight: bold;
  margin-left: 10rpx;
}

.payment-btn {
  width: 240rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background-color: #007AFF;
  color: #FFFFFF;
  font-size: 30rpx;
  line-height: 80rpx;
  margin: 0;
  padding: 0;
}

.payment-btn.disabled {
  background-color: #CCCCCC;
}

.debug-info {
  background-color: #FFF5E6;
  padding: 10rpx 20rpx;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #FF9500;
}

.safe-area-inset-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.backup-btn-area {
  margin-top: 60rpx;
  padding: 30rpx;
}

.backup-payment-btn {
  width: 100%;
  height: 90rpx;
  border-radius: 45rpx;
  background-color: #007AFF;
  color: #FFFFFF;
  font-size: 32rpx;
  line-height: 90rpx;
  margin: 0;
  padding: 0;
}

.backup-payment-btn.disabled {
  background-color: #CCCCCC;
}
</style> 